/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.workflow.controller;

import offset.nodes.server.workflow.controller.dispatch.WorkflowDispatchAttribute;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import offset.nodes.Constants;
import offset.nodes.server.controller.AuthenticatingAction;
import offset.nodes.server.dispatch.controller.DispatchAttribute;
import offset.nodes.server.controller.EditorAttribute;
import offset.nodes.server.error.model.LoggedException;
import offset.nodes.server.version.model.FrozenNode;
import offset.nodes.server.workflow.model.State;
import offset.nodes.server.workflow.model.Workflow;
import offset.nodes.server.workflow.model.WorkflowDocument;
import offset.nodes.server.workflow.model.WorkflowExceptionId;
import offset.nodes.server.workflow.model.WorkflowModel;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Walter L�tgenau
 */
public class WorkflowAction extends AuthenticatingAction {

    /**
     * Entry point for all workflow actions. What is done, depends on the situation: Create a new workflow document, forward to an existing state (e.g. from a user query), do a workflow
     * transition.
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return the forward to the appropriate display for the state
     * @throws Exception
     */
    @Override
    public ActionForward process(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        WorkflowForm workflowForm = (WorkflowForm) form;
        WorkflowModel model = new WorkflowModel(getRepositorySession(request));

         if (request.getAttribute(WorkflowDispatchAttribute.ATT_WORKFLOW_DISPATCH) != null)
            workflowForm.setRef(((WorkflowDispatchAttribute) request.getAttribute(WorkflowDispatchAttribute.ATT_WORKFLOW_DISPATCH)).getRef());
            
        // get node
        Node node = null;
        DispatchAttribute dispatchAttribute = (DispatchAttribute) request.getAttribute(DispatchAttribute.ATT_DISPATCH);
        if (dispatchAttribute.getNode() != null)
            node = dispatchAttribute.getNode();
        else
            node = model.getNodeByUuid(workflowForm.getRef());

        // is this a workflow node
        ActionForward forward = null;
        if (node.isNodeType(Constants.TYPE_WORKFLOW)) {
            Workflow workflow = model.getWorkflow(node);
            forward = forwardToCreationState(model, mapping, workflowForm, request, workflow);
        } else if (node.isNodeType(Constants.TYPE_WORKFLOW_DOCUMENT)) { // is this is a workflow document node
            WorkflowDocument workflowDocument = model.getWorkflowDocument(node, request);
            if (workflowForm.getTransition() != null ) // transition directly requested
                 forward = doTransition(model, mapping, workflowForm, request, workflowDocument); // transition requested
            else if (workflowForm.getResult() != null && isInEditorState(workflowDocument) && !(node instanceof FrozenNode)) {
                forward = doEditorTransition(model, mapping, workflowForm, request, workflowDocument);
            } else
                forward = forwardToCurrentState(model, mapping, workflowForm, request, workflowDocument); // no transition requested
        } else if (model.isWorkflowDocumentSubNode(node)) { // is this a subnode of a workflow document
            Node workflowDocumentNode = model.getWorkflowDocumentNodeFromSubNode(node);
            WorkflowDocument workflowDocument = model.getWorkflowDocument(workflowDocumentNode, request);
            if (workflowForm.getTransition() != null)
                forward = doTransition(model, mapping, workflowForm, request, workflowDocument);
        }

        if (forward == null)
            throw new LoggedException(WorkflowExceptionId.NO_PERMISSION_FOR_CURRENT_STATE);

        return forward;
    }

    /**
     * Find the creation state among the workflow states. Check, if it is available for the current user. If it is,
     * determine the forward appropriate for the state and return it. Else forward to the error page.
     *
     * @param model
     * @param mapping
     * @param form
     * @param request
     * @param workflow
     * @return the forward to the creation state
     */
    protected ActionForward forwardToCreationState(WorkflowModel model, ActionMapping mapping, WorkflowForm form, HttpServletRequest request, Workflow workflow) throws RepositoryException {
        State creationState = null;

        Iterator<State> i = workflow.getStates().values().iterator();
        while (i.hasNext()) {
            State state = i.next();
            if (state.isNewState() && model.isPermitted(state)) {
                creationState = state;
                break;
            }
        }

        if (creationState != null)
            return forwardToState(model, mapping, form, request, creationState, new WorkflowDocument(null, workflow, creationState.getName()));

        throw new LoggedException(WorkflowExceptionId.NO_CREATION_STATE);
    }

    /**
     * Check, if the current state has only a single transition.
     *
     * In this case, do exactly the same as if the transition would have been requested directly,
     * i.e. store the transition name in the form.
     *
     * @param workflowDocument
     * @param workflowForm
     * @return true, if there is only a single transition. Else false
     */
    protected boolean isInEditorState(WorkflowDocument workflowDocument) {
        State currentState = workflowDocument.getWorkflow().getStates().get(workflowDocument.getCurrentState());
        if ((currentState.getTransitionNames().size() == 1 || currentState.getTransitionNames().size() == 2)
                && currentState.isDirectEdit()) {
            return true;
        }

        return false;
    }

    protected ActionForward doEditorTransition(WorkflowModel model, ActionMapping mapping, WorkflowForm form, HttpServletRequest request, WorkflowDocument workflowDocument) throws RepositoryException {
        State currentState = workflowDocument.getWorkflow().getStates().get(workflowDocument.getCurrentState());
        if (form.getResult().equals(Constants.PARVALUE_OK))
            form.setTransition(currentState.getTransitionNames().get(0));
        else if (form.getResult().equals(Constants.PARVALUE_CANCEL)) {
            if (currentState.getTransitionNames().size() == 1)
                form.setTransition(currentState.getTransitionNames().get(0));
            else
                form.setTransition(currentState.getTransitionNames().get(1));
        }

        return doTransition(model, mapping, form, request, workflowDocument);
    }

    /**
     * Check, if the transition state is available for the user. If it is, determine the forward appropriate for the state and return it. If not,
     * return the forwardToCurrentState.
     *
     * @param model
     * @param mapping
     * @param form
     * @param request
     * @param workflowDocument
     * @return the forward to the requested transition state in case of success. Else either a forward to the current or the creation state or an error page.
     */
    protected ActionForward doTransition(WorkflowModel model, ActionMapping mapping, WorkflowForm form, HttpServletRequest request, WorkflowDocument workflowDocument) throws RepositoryException {
        State requestedTransitionState = workflowDocument.getWorkflow().getStates().get(form.getTransition());
        State currentState = workflowDocument.getWorkflow().getStates().get(workflowDocument.getCurrentState());

        if (model.isPermitted(requestedTransitionState)) {
            if (!isCreateSubDocument(requestedTransitionState))
                model.updateState(workflowDocument, requestedTransitionState);
            return forwardToState(model, mapping, form, request, requestedTransitionState, workflowDocument);
        } else if (model.isPermitted(currentState))
            return forwardToState(model, mapping, form, request, currentState, workflowDocument);

        throw new LoggedException(WorkflowExceptionId.NO_PERMISSION_FOR_STATE, new Object[]{requestedTransitionState.getName()});
    }

    /**
     * Does the state create a subdocument?
     *
     * In this case, no transition will be done for the parent document.
     * 
     * @param state
     * @return
     */
    protected boolean isCreateSubDocument(State state) {
        return state.getVirtualPageInstanceUUID() != null && state.getRelativePath() != null;
    }

    /**
     * Check, if the current  state is available for the user. If it is, determine the appropriate forward and return it. Else forward to the creation page and
     * if this is not available as well, to the error page.
     *
     * @param model
     * @param mapping
     * @param form
     * @param request
     * @param workflowDocument
     * @return the forward to the current state, if permitted.
     */
    protected ActionForward forwardToCurrentState(WorkflowModel model, ActionMapping mapping, WorkflowForm form, HttpServletRequest request, WorkflowDocument workflowDocument) throws RepositoryException {
        State currentState = workflowDocument.getWorkflow().getStates().get(workflowDocument.getCurrentState());

        return forwardToState(model, mapping, form, request, currentState, workflowDocument);
    }

    protected ActionForward forwardToState(WorkflowModel model, ActionMapping mapping, WorkflowForm workflowForm,
            HttpServletRequest request, State state, WorkflowDocument workflowDocument) throws RepositoryException {
        WorkflowAttribute workflowAttribute = new WorkflowAttribute(workflowDocument);
        for (String transitionName : state.getTransitionNames()) {
            State transition = workflowDocument.getWorkflow().getStates().get(transitionName);
            if (model.isPermitted(transition))
                workflowAttribute.getStates().add(transition);
        }

        request.setAttribute(workflowAttribute.getId(), workflowAttribute);

        // template instance editor
        if (state.getVirtualPageInstanceUUID() != null) {
            ActionForward forward = null;
            
            if (workflowDocument.getNode() == null || state.getRelativePath() != null) { // new workflow node shall be created
                if (state.isTree()) {
                    forward = createTreeForward(state, model, mapping, workflowForm, workflowDocument);
                    forward.setRedirect(true);
                    request.getSession().setAttribute(workflowAttribute.getId(), workflowAttribute); // must be put into the session in this case, because of the redirect
                } else {
                    String nodeType = model.getNodeByUuid(state.getVirtualPageInstanceUUID()).getProperty(Constants.PROP_NODETYPE).getString();
                    Node newNode = model.newNode(workflowDocument.getNode().getPath(), "NEW", nodeType);
                    forward = createPageForward(newNode.getUUID(), state, mapping, workflowDocument, workflowForm, request);
                }
            } else {
                forward = createPageForward(workflowDocument.getNode().getUUID(), state, mapping, workflowDocument, workflowForm, request);
            }

            return forward;
        } // component editor
        else if (state.getRelativePath() != null) {
            // create forward to component editor
            String path = mapping.findForward("path.repository").getPath() + workflowDocument.getNode().getPath() + "/" + state.getRelativePath();

            ActionForward forward = new ActionForward(path);
            forward = addParameter(forward, Constants.PAR_CONTENT_TYPE, state.getContentType());

            // create editor attribute for backward forward
            EditorAttribute editorAttribute = new EditorAttribute();

            ActionForward returnUrl = new ActionForward();
            returnUrl.setPath(getRepositoryUrl(request));
            returnUrl = addParameter(returnUrl, Constants.PAR_DATA_REFERENCE, workflowDocument.getNode().getUUID());
            returnUrl = addParameter(returnUrl, Constants.PAR_CONTENT_TYPE, Constants.CONTENT_TYPE_WORKFLOW);
            returnUrl.setRedirect(true);
            editorAttribute.setReturnUrl(returnUrl.getPath());

            request.setAttribute(editorAttribute.getId(), editorAttribute);

            return forward;
        }

        throw new LoggedException(WorkflowExceptionId.NO_PERMISSION_FOR_STATE, new Object[]{state.getName()});
    }

    protected ActionForward createPageForward(String uuid, State state, ActionMapping mapping, WorkflowDocument workflowDocument, WorkflowForm workflowForm, HttpServletRequest request) throws RepositoryException {
        ActionForward forward = mapping.findForward("path.repository");

        forward = addParameter(forward, Constants.PAR_DATA_REFERENCE, uuid);
        forward = addParameter(forward, Constants.PAR_TEMPLATE_INSTANCE_REFERENCE, state.getVirtualPageInstanceUUID());
        if (state.isDirectEdit() && workflowForm.getVref() == null) // if vref present, this is a request from the virtual edit applet
            request.setAttribute(EditorAttribute.ATT_EDITOR, new EditorAttribute());
        forward = addParameter(forward, Constants.PAR_CONTENT_TYPE, Constants.CONTENT_TYPE_VIRTUAL);

        return forward;

    }

    /**
     * Create the necessary forward for a virtual tree
     * 
     * @param state
     * @param model
     * @param mapping
     * @param workflowForm
     * @param workflowDocument
     * @return
     * @throws RepositoryException
     */
    protected ActionForward createTreeForward(State state, WorkflowModel model, ActionMapping mapping, WorkflowForm workflowForm, WorkflowDocument workflowDocument) throws RepositoryException {
        ActionForward forward = new ActionForward();
        forward.setPath(mapping.findForward("path.repository").getPath() + model.getCreationPath(state.getVirtualPageInstanceUUID()) + "/NEW");

        if (state.getRelativePath() != null)
            forward = addParameter(forward, Constants.PAR_DIR, workflowDocument.getNode().getPath() + "/" + state.getRelativePath());

        if (state.isDirectEdit() && workflowForm.getVref() == null) // if vref present, this is a request from the virtual edit applet
            forward = addParameter(forward, Constants.PAR_MODE, Constants.PARVALUE_EDIT);

        return forward;
    }

     /**
     * Extract the repository path from the request URL
     * 
     * @param request
     * @return
     * @throws RepositoryException
     */
    protected String getRepositoryUrl(HttpServletRequest request) throws RepositoryException {
        URL requestUrl;
        try {
            requestUrl = new URL(request.getRequestURL().toString());
            String[] folders = requestUrl.getPath().split("/");
            String path = "/";
            if (folders.length >= 3)
                path = path + folders[1] + "/" + folders[2];
            return new URL(requestUrl.getProtocol(), requestUrl.getHost(), requestUrl.getPort(), path).toString();
        } catch (MalformedURLException ex) {
            throw new RepositoryException(ex);
        }
    }
}
